<template>
  <div class="section" style="margin-top: 5rem">
    <div class="columns is-centered">
      <div class="column is-one-third box" style="padding: 2.5rem">
        <div class="has-text-centered">
          <img src="/img/logo.svg" alt>
        </div>
        <h2 class="has-text-centered title has-text-grey-dark">请登录</h2>
        <form @submit.prevent="submitLogin">
          <div class="field">
            <p class="control has-icons-left has-icons-right">
              <input class="input" type="text" v-model="username" placeholder="请输入用户名">
              <span class="icon is-small is-left">
                <i class="iconfont icon-user"></i>
              </span>
            </p>
          </div>
          <div class="field">
            <p class="control has-icons-left">
              <input class="input" type="password" v-model="password" placeholder="请输入密码">
              <span class="icon is-small is-left">
                <i class="iconfont icon-password"></i>
              </span>
            </p>
          </div>
          <div class="field">
            <p class="control has-text-centered">
              <button class="button is-medium is-primary is-fullwidth">
                <i class="iconfont icon-login" style="margin-right:0.5rem"></i>
                登录
              </button>
            </p>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { login } from "../api";
import { getCookie, setCookie, flash } from "../functions";
export default {
  data() {
    return {
      username: "",
      password: ""
    };
  },
  created() {
    if (getCookie("user")) {
      this.$router.push({ path: "/admin" });
    }
  },
  methods: {
    submitLogin() {
      login(
        {
          username: this.username,
          password: this.password
        },
        res => {
          if (res.data.code === 200) {
            setCookie("user", this.username, 7);
            this.$router.push({ path: "/admin" });
            flash("登录成功！");
          } else {
            flash("登录失败！");
          }
        }
      );
    }
  }
};
</script>

